<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert show-icon type="warning" title="注意:只允许为三级分类设置相关参数" :closable="false"></el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader expand-trigger="hover" :options="cateList" :props="catePorps" v-model="selectCateKeys" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtDisabled" @click="addParamDialog">添加参数</el-button>
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag  v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="openEditParamDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="delParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtDisabled" @click="addParamDialog">添加属性</el-button>
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag  v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="openEditParamDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="delParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="'添加' + titleText.title"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <el-form :model="addParamData" :rules="addParamRules" ref="addParamRef" label-width="100px">
        <el-form-item :label="titleText.title" prop="p_name">
          <el-input v-model="addParamData.p_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="'编辑'+ titleText.title"
      :visible.sync="editParamDialogVisible"
      width="50%">
      <el-form :model="editParamData" :rules="editParamRules" ref="editParamRef" label-width="100px">
        <el-form-item :label="titleText.title" prop="p_name">
          <el-input v-model="editParamData.p_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParam">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [],
      catePorps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectCateKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addParamsDialogVisible: false,
      addParamData: {
        p_name: ''
      },
      addParamRules: {
        p_name: [
          { required: true, message: '请输入参数名', trigger: 'blur' }
        ]
      },
      editParamDialogVisible: false,
      editParamData: {
        p_id: '',
        p_name: ''
      },
      editParamRules: {
        p_name: [
          { required: true, message: '请输入参数名', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品信息失败')
      this.cateList = res.data
      console.log(res.data)
    },
    handleChange () {
      this.getParamsData()
    },
    handleTabClick () {
      this.getParamsData()
    },
    async getParamsData () {
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateID}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数信息失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    addParamDialog () {
      this.addParamsDialogVisible = true
    },
    addDialogClosed () {
      this.$refs.addParamRef.resetFields()
    },
    addParam () {
      this.$refs.addParamRef.validate(async valid => {
        if (!valid) return this.$message.error('添加参数失败')
        const { data: res } = await this.$http.post(`categories/${this.cateID}/attributes`, {
          attr_name: this.addParamData.p_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.addParamsDialogVisible = false
        this.getParamsData()
      })
    },
    openEditParamDialog (attrid) {
      this.selectParamByID(attrid)
      this.editParamDialogVisible = true
    },
    editParam () {
      this.$refs.editParamRef.validate(async valid => {
        if (!valid) return this.$message.error('修改属性失败')
        const { data: res } = await this.$http.put(`categories/${this.cateID}/attributes/${this.editParamData.p_id}`, { attr_name: this.editParamData.p_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('修改属性失败')
        this.$message.success('修改属性成功')
        this.getParamsData()
        this.editParamDialogVisible = false
      })
    },
    async selectParamByID (attrid) {
      const { data: res } = await this.$http.get(`categories/${this.cateID}/attributes/${attrid}`)
      if (res.meta.status !== 200) return this.$message.error('获取属性失败')
      this.editParamData.p_id = res.data.attr_id
      this.editParamData.p_name = res.data.attr_name
    },
    async delParam (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消')
      const { data: res } = await this.$http.delete(`categories/${this.cateID}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除属性失败')
      this.$message.success('删除属性成功')
      this.getParamsData()
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      const { data: res } = await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(',')
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('添加成功')
    },
    async handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
    }
  },
  computed: {
    isBtDisabled () {
      return this.selectCateKeys.length !== 3
    },
    cateID () {
      if (this.selectCateKeys) {
        return this.selectCateKeys[2]
      } return null
    },
    titleText () {
      return {
        title: this.activeName === 'many' ? '动态参数' : '静态属性'
      }
    }
  }
}
</script>

<style>
  .el-row{
    margin: 15px 0;
  }
  .el-cascader{
    width: 250px;
  }
  .el-tag{
    margin: 10px;
  }
  .input-new-tag{
    width: 120px !important;
  }
</style>
